export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);

    const echartsScriptTag = document.createElement('script');
    echartsScriptTag.src = 'https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js';
    document.head.appendChild(echartsScriptTag);

    const self = this;

    const ddcatSources = [
        { id: "ds_mod:b49a09d0-f3ce-4706-89b3-0f9c0df5e40e", name: "检查任务-检查任务趋势" },
        { id: "ds_mod:f2912034-e78a-49eb-b828-a06f615126a8", name: "专项检查计划- 时间分布" }
    ];

    // 加载检查任务-检查任务趋势 折线图
    fetchDdcatData(ddcatSources[0].id).then(res => {
        if (res && res.length) {
            loadTaskTrendLineChart(self, res);
        } else {
            // 数据为空，使用模拟数据
            const mockData = generateMockInspectionPlanData();;
            loadTaskTrendLineChart(self, mockData);
        }
    });

}


/**
 * 加载检查任务趋势折线图
 */
function loadTaskTrendLineChart(self, data) {
    const chartContainer = self.$$("text_h4r5qt").$el;
    const myChart = echarts.init(chartContainer);

    // 把数据按照月份归类
    const monthMap = {};
    debugger
    data.forEach(item => {
        let timeStr = item.planTime;
        const month = timeStr.slice(0, 7);
        const planCount = item.planCount || 0;
        monthMap[month] = (monthMap[month] || 0) + planCount;
    });

    const months = Object.keys(monthMap).sort();
    const counts = months.map(m => monthMap[m]);

    const option = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: months,
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                rotate: 0,
                color: 'rgba(0, 0, 0, 0.5)'
            },
            boundaryGap: false
        },
        yAxis: {
            type: 'value'
        },
        grid: {
            left: '10%',
            right: '8%',
            bottom: '20%',
            top: '10%'
        },
        series: [{
            type: 'line',
            data: [counts[0] - 10, ...counts],
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#3399FF' },
                    { offset: 1, color: '#66CCFF' }
                ]),
                borderWidth: 2
            },
            lineStyle: {
                width: 2,
                type: 'solid'
            },
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            areaStyle: {
                type: 'linear',
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(51, 136, 255, 0.1)' },
                    { offset: 1, color: 'rgba(51, 136, 255, 0)' }
                ])
            },
            shadowColor: 'rgba(51, 136, 255, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 2
        }]
    };

    myChart.setOption(option);
}

/**
 * 从 ddcat 数据源拉取所有数据
 * @returns Promise<数组> - 返回结果数组
 */
function fetchDdcatData(sourceId) {
    const jsonParams = { pageSize: 99999 };
    return api.DATA_SOURCE_EXECUTE(
        sourceId,
        "ddcat",
        [],
        [],
        JSON.stringify(jsonParams)
    ).then(res => {

        if (res && !res.hasError && res.result != null) {
            return res.result;
        } else {
            console.warn("查询失败或数据为空，生成模拟数据");
            // 这里生成模拟数据
            return generateMockInspectionPlanData();
        }
    });
}

/**
 * 获取当前月往前推六个月的模拟数据
 * 数据包含时间（planTime）和检查计划个数（planCount）
 */
function generateMockInspectionPlanData() {
    const mockData = [];
    const currentDate = new Date();

    // 获取过去六个月的月份
    for (let i = 0; i < 6; i++) {
        const month = new Date(currentDate);
        month.setMonth(month.getMonth() - i);
        const monthStr = month.toISOString().slice(0, 7);

        mockData.push({
            planTime: monthStr + '-01',
            planCount: Math.round(Math.random() * 100 + 50)
        });
    }

    return mockData;
}
